<?php
//$password = $_GET['a'];
//echo md5(md5($password) . '1111');


$total = 550000;//总贷款
$balance = 200000;//结余金额
$wage = 5000;
$interest = 0.0588;//贷款利率
$interest2 = 0.12;//理财年收益
$time = 20;//贷款年限
$type = 2;//1等额本金 2 等额本息
$interest = $interest / 12;

$already = 0;
$month = 0;
switch ($type){
    case 1:
        safe_money($total,$time,$interest,$balance,$interest2,$wage);
        break;
    case 2:
        safe_interest($total,$time,$interest,$balance,$interest2,$wage);
        break;

}


function safe_money($total,$time,$interest,$balance,$interest2,$wage){
    $m_money = $total / $time / 12;
    $all = 0;
    echo "<pre>";
    for ($i = 1; $i <= $time * 12; $i++) {
        $i_money = $total * $interest;


        $month = $i_money + $m_money;
        $all += $month;
        echo "第{$i}月，还款总额：{$month} 其中 利息 {$i_money} 本金 {$m_money}" . PHP_EOL;
        echo "总还款 {$all}".PHP_EOL;
        $total = $total - $m_money;
        $balance =$balance + $wage- $month;

        if($i == 12 ){
            if($total > $balance){
                $total = $total - $balance;
                $balance = 0;
            }else{
                $total = 0;
                $balance = $balance - $total;
            }
        }
        //每年收益
        if($i % 12 == 0){
            $balance = $balance *(1+$interest2);
        }
        echo "总可用资金：{$balance}".PHP_EOL;
    }

}

function safe_interest($total,$time,$interest,$balance,$interest2,$wage){
//贷款本金×月利率×(1+月利率)^还款月数〕÷〔(1+月利率)^还款月数-1〕。
    $all = 0;
    echo "<pre>";
   for($i = 1;$i< $time*12;$i++){
       $month  = $total * $interest * pow((1+$interest),$time*12) /  (pow((1+$interest),$time*12)-1);
       $all += $month;
       echo "第{$i}月，还款总额：{$month} " . PHP_EOL;
       echo "总还款 {$all}".PHP_EOL;

       $balance = $balance+$wage- $month;

       if($i == 12 ){
           if($total > $balance){
               $total = $total - $balance;
               $balance = 0;
           }else{
               $total = 0;
               $balance = $balance - $total;
           }
       }

       //每年收益
       if($i % 12 == 0){
           $balance = $balance *(1+$interest2);
       }
       echo "总可用资金：{$balance}".PHP_EOL;

   }
}